package xyz.playedu.resource.utils;

import org.springframework.stereotype.Service;
import xyz.playedu.resource.domain.ResourceTextNode;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResourceTextHelper {


    /**
     * 更新节点释放根节点
     * @param resourceTextNodeList
     * @return
     */
    public List<ResourceTextNode> processResourceTextChildNode(List<ResourceTextNode> resourceTextNodeList){
        List<ResourceTextNode> newResourceTextNdoes=new ArrayList<>();
        for(int i=0;i<resourceTextNodeList.size();i++){
            if(i==0){
                resourceTextNodeList.get(i).setRoot(true);
            }else{
                ResourceTextNode resourceTextNode = this.getLasetResourceTextNode(i,resourceTextNodeList);
                if(resourceTextNode==null){
                    resourceTextNodeList.get(i).setRoot(true);
                }else{
                    resourceTextNodeList.get(i).setRoot(false);
                    resourceTextNode.getChildren().add(resourceTextNodeList.get(i));
                }
            }
        }
        return newResourceTextNdoes;
    }

    public ResourceTextNode getLasetResourceTextNode(int iCurNodeNum,List<ResourceTextNode> resourceTextNodes){
            int i = iCurNodeNum-1;
            int iElementNum = resourceTextNodes.get(iCurNodeNum).getElementNum();
            while(i>0){
                if(resourceTextNodes.get(i).getElementNum()<iElementNum){
                    resourceTextNodes.get(iCurNodeNum).setRoot(false);
                    return resourceTextNodes.get(i);
                }else{
                    i--;
                }
            }
            return null;
    }


}
